#include "comm.hpp"
#include <cstring>

Init init;

string TransToHex(key_t k)
{
    char buffer[32];
    snprintf(buffer, sizeof buffer, "0x%x", k);
    return buffer;
}

int main()
{
    //1.创建公共的Key值
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("creat key done", Debug) << " server key : " << k << endl;
    
    //2.创建共享内存 -- 建议要创建一个全新的共享内存 -- 通信的发起者
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(1);
    }
    Log("creat shm done", Debug) << " shmid : " << shmid << endl;

    //3.将指定的共享内容，挂接到自己的地址空间
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    Log("attach shm done", Debug) << " shmid : " << shmid << endl;


    //将共享内存当成一个大字符串
    //char buffer[SHM_SIZE];

    int fd = OpenFIFO(FIFO_NAME, READ);

    for (;;)
    {
        Wait(fd);
        //临界区
        if (strcmp(shmaddr, "quit") == 0) break;
        cout << "Client say : ";
        printf("%s\n", shmaddr);
        //sleep(1);
    }

    //4.将指定的共享内存从自己的地址空间中去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    (void)n;
    Log("detach shm done", Debug) << " shmid : " << shmid << endl;

    //last.删除共享内存
    n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    (void)n;
    Log("delete shm done", Debug) << " shmid : " << shmid << endl;
    
    CloseFifo(fd);

    return 0;
}